package com.qipay.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * ip代理帮助类
 */
public class ProxyUtil {
    private static Logger logger = LoggerFactory.getLogger(ProxyUtil.class);
    //    private final static String orderId = "996722816923713";
//    public final static String userName = "707777894";
//    public final static String userPwd = "0qskuf8u";
//    private final static String key = "o1xo5334g1nr4sa2m0fvjiphgtn2pgv3";

    private static void getProxyList(String orderId) {
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://dps.kdlapi.com/api/getdps/?orderid=" + orderId + "&num=10&pt=1&dedup=1&format=json&sep=1")
                    .get()
                    .build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            logger.info("提取代理IP返回：" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (jsonObject.getInteger("code") == 0) {
                JSONArray proxyList = jsonObject.getJSONObject("data").getJSONArray("proxy_list");
                LocalCache.setCache("proxyList", proxyList, 60);
            }
        } catch (Exception e) {
            logger.info("获取私密代理列表失败：" + e);
        }
    }

    private static String getProxy(String orderId, String orderKey) {
        if (!LocalCache.contains("proxyList") && !LocalCache.contains("getProxy")) {
            LocalCache.setCache("getProxy", 1, 30);
            getProxyList(orderId);
        }
        JSONArray proxyList = LocalCache.getCache("proxyList");
        Random random = new Random();
        if (proxyList != null && proxyList.size() > 0) {
//            boolean flag = true;
//            String proxy = "";
//            while (flag) {
                int index = random.nextInt(proxyList.size());
//                proxy = proxyList.getString(index);
//                if (!checkProxy(proxy, orderId, orderKey)) continue;
//                flag = false;
//            }
            return proxyList.getString(index);
        }
        return "error";
    }

    private static boolean checkProxy(String proxy, String orderId, String orderKey) {
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("https://dps.kdlapi.com/api/checkdpsvalid?orderid=" + orderId + "&signature=" + orderKey + "&proxy=" + proxy)
                    .get()
                    .build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (jsonObject.getInteger("code") == 0) {
                JSONObject dataJson = jsonObject.getJSONObject("data");
                return dataJson.getBoolean(proxy);
            }
            return false;
        } catch (Exception e) {
            logger.info("检测代理有效性失败：" + e);
            return false;
        }
    }

    public static OkHttpClient getOkHttp(String[] proxyInfos, String tradeNo) {
        String proxyStr = ProxyUtil.getProxy(proxyInfos[0], proxyInfos[1]);
        OkHttpClient client;
        if (proxyStr.equals("error")) {
            logger.info("订单号：" + tradeNo + "获取代理ip失败!");
            client = new OkHttpClient();
        } else {
            String[] proxyIps = proxyStr.split(":");
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIps[0], Integer.parseInt(proxyIps[1])));
            Authenticator proxyAuthenticator = (route, response) -> {
                String credential = Credentials.basic(proxyInfos[2], proxyInfos[3]);
                return response.request().newBuilder()
                        .header("Proxy-Authorization", credential)
                        .build();
            };
            client = new OkHttpClient().newBuilder().
                    connectTimeout(120, TimeUnit.SECONDS).readTimeout(120, TimeUnit.SECONDS).proxy(proxy)
                    .proxyAuthenticator(proxyAuthenticator)
                    // 解决内存溢出问题
                    .connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS)).build();
        }
        return client;
    }
}
